require 'KonaLast/version'
require 'net/http'
require 'net/https'
require 'json'
require 'optparse'

module KonaLast

  class Utils
    MAX_IMGS = 100

    # @return [Hash] with options
    def options(args)
      options = {}
      # defaults
      # @todo: load defaults from file
      options[:limit] = '5'
      options[:api] = URI('http://konachan.com/post.json')
      parser = OptionParser.new do |o|

        o.on('-n', '--number', '=[OPTIONAL]', Integer,'Num of images to be retrieved. Integer.') do |number|
          if number > MAX_IMGS
            warn "#{number} is too much, I'll give you just 5"
            number = 5
          end
          options[:limit] = number.to_s
        end

        # @todo: validate input url
        o.on('--url', '=[OPTIONAL]', 'API\'s URL, dont validates yet. Be careful') do |url|
          options[:api] = URI(url)
        end

        o.on_tail('--version', 'Show version.') do
          KonaLast::Version.show_version(true)
          exit
        end

        o.on_tail('-h', '--help', 'Show this helpful message.') do
          puts o
          exit
        end

      end

      parser.parse!(args)
      options

    end

    # @return [Hash] translated from JSON
    def translate(json)
      JSON.parse(json)
    end

    # @return [String] with the """pretty output"""
    # @todo: prettify the output
    def print(message)
      message.each do |image|
        puts shorten(image['file_url'])
      end
    end

    # return [String] shorten url with goo.gl
    def shorten(long_url)
      uri = URI.parse('https://www.googleapis.com/urlshortener/v1/url')
      googl_san = Net::HTTP.new(uri.host, uri.port)
      googl_san.use_ssl = true
      # rubymine gives me a warning about OpenSSL::SSL::VERIFY_NONE
      # fu.
      googl_san.verify_mode = OpenSSL::SSL::VERIFY_NONE

      # rubymine gives me a "String as hash key" warning
      # fu.
      # fu again.
      initheader = {'Content-Type' =>'application/json'}

      question = Net::HTTP::Post.new(uri.request_uri, initheader)
      question.body = {longUrl: long_url}.to_json
      response = googl_san.request(question)
      translate(response.body)['id']

    end
  end

  class Site

    # @return [JSON] if everything is ok
    # @todo: escape empty response
    def ask(options)
      response = Net::HTTP.post_form(options[:api], 'limit' => options[:limit])
      response.body
    end

  end
end